import json

from django.core.paginator import Paginator
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from goods.models import GoodsCategory, SKU
from goods.utils import get_breadcrumb


class GoodsListView(View):
    def get(self,request,category_id):
        page=request.GET.get('page')
        page_size=request.GET.get('page_size')
        ordering=request.GET.get('ordering')

        try:
            category=GoodsCategory.objects.get(id=category_id)
        except Exception as e:
            return JsonResponse({'code':400,
                                 'errmsg':'商品分类id错误'})
        try:
            skus=SKU.objects.filter(category=category,
                                    is_launched=True).order_by(ordering)
        except Exception as e:
            return JsonResponse({'code':400,
                                 'errmsg':'获取商品失败'})

        paginator=Paginator(skus,page_size)

        shown_skus=paginator.page(page)

        page_number=paginator.num_pages

        list=[]

        breadcrumb=get_breadcrumb(category)

        for sku in shown_skus:
            list.append({
                'id':sku.id,
                'default_image_url':sku.default_image_url,
                'name':sku.name,
                'price':sku.price
            })
        return JsonResponse({'code':0,
                             'errmsg':'ok',
                             'count':page_number,
                             'breadcrumb': breadcrumb,
                             'list':list})

class HotGoodsView(View):
    """商品热销排行"""

    def get(self, request, category_id):
        """提供商品热销排行 JSON 数据"""
        # 根据销量倒序
        try:
            skus = SKU.objects.filter(category_id=category_id,
                                  is_launched=True).order_by('-sales')[:2]
        except Exception as e:
            return JsonResponse({'code':400,
                                 'errmsg':'获取商品出错'})
        # 转换格式:
        hot_skus = []
        for sku in skus:
            hot_skus.append({
                'id':sku.id,
                'default_image_url':sku.default_image_url,
                'name':sku.name,
                'price':sku.price
            })

        return JsonResponse({'code':0,
                             'errmsg':'OK',
                             'hot_skus':hot_skus})


from haystack.views import SearchView

class MySearchView(SearchView):
    '''重写SearchView类'''
    def create_response(self):
        page = self.request.GET.get('page')
        # 获取搜索结果
        context = self.get_context()
        data_list = []
        for sku in context['page'].object_list:
            data_list.append({
                'id':sku.object.id,
                'name':sku.object.name,
                'price':sku.object.price,
                'default_image_url':sku.object.default_image_url,
                'searchkey':context.get('query'),
                'page_size':context['page'].paginator.num_pages,
                'count':context['page'].paginator.count
            })
        # 拼接参数, 返回
        return JsonResponse(data_list, safe=False)

class UserBrowseHistory(View):
    def post(self,request):
        #保存用户浏览信息到redis
        dict=json.loads(request.body.decode())
        sku_id=dict.get('sku_id')
        user_id=request.user.id
        try:
            sku=SKU.objects.get(id=sku_id)
        except Exception as e:
            return JsonResponse({'code':400,
                                 'errmsg':'查询商品失败'})

        redis_conn=get_redis_connection('history')

        pl=redis_conn.pipeline()
        pl.lrem(user_id,0,sku_id)
        pl.lpush(user_id,sku_id)
        pl.ltrim(user_id,0,4)
        pl.execute()

        return JsonResponse({'code': 0,
                             'errmsg': 'OK'})
    def get(self,request):
        #从redis获取用户浏览信息，返回数据给前端页面
        redis_conn=get_redis_connection('history')
        sku_ids=redis_conn.lrange(request.user.id,0,-1)
        skus = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            skus.append({
                'id': sku.id,
                'name': sku.name,
                'default_image_url': sku.default_image_url,
                'price': sku.price
            })

        return JsonResponse({'code': 0,
                             'errmsg': 'OK',
                             'skus': skus})